﻿$.fn.validationCodeButton = function (options) {
    var defaults = {
        limit: 60,
        url: "",
        codeType: "",
        phone: $("#PhoneNumber"),
        success: function () {
            show_message("验证码已发送到手机，请注意查收");
        },
        fail: function () {
            show_message("验证码获取失败，请重试", "error");
        }
    };
    var validationSetting = $.extend(defaults, options);
    var validationInterval;
    $(this).attr("data-canget", 1);
    validationSetting.btn = $(this);
    validationSetting.countDown = 0;
    window.validationSetting = validationSetting;
    resetCountDown();
    $(".request-validation").click(function () {
        var phoneNumber = $(validationSetting.phone).val();
        if (phoneNumber.length == 0) {
            show_message('手机号码不可为空', "warning");
        } else if (!(/^1[3|4|5|7|8][0-9]\d{8}$/.test(phoneNumber))) {
            show_message('手机号码格式不正确', "warning");
        }
        else {
            var btn = $(this);
            var canGet = ~~btn.attr("data-canget");
            if (canGet == 1) {
                btn.attr("data-canget", 0);
                $.ajax({
                    url: validationSetting.url,
                    type: "POST",
                    data: AntiCSRF({ type: validationSetting.codeType, phone: phoneNumber }),
                    dataType: "JSON",
                    success: function (data) {
                        console.log(data);
                        if (data.code == 1) {
                            btn.attr("disabled", "disabled");
                            validationSetting.validationInterval = setInterval(validationCountDown, 1000, btn);
                            validationSetting.success();
                        }
                        else {
                            btn.attr("data-canget", 1);
                            validationSetting.fail();
                        }
                    }
                });
            }
        }
    });
}

function resetCountDown() {
    var setting = window.validationSetting;
    setting.countDown = setting.limit;
}

function validationCountDown(para) {
    var setting = window.validationSetting;
    var btn = $(para);
    btn.text(setting.countDown + "秒后重试");
    setting.countDown--;
    if (setting.countDown < 0) {
        btn.removeAttr("disabled");
        btn.attr("data-canget", 1);
        btn.text("获取验证码");
        clearInterval(setting.validationInterval);
        resetCountDown();
    }
}